package cn.nawang.ebeim.ui.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

import cn.nawang.ebeim.ui.bean.Datasource;
import cn.nawang.ebeim.ui.bean.DatasourceConfig;


public class RestUtil {
  private static final Logger LOG = LoggerFactory.getLogger(RestUtil.class);
  private String host;
  private int port;
  
  public RestUtil(String host, int port) {
    this.host = host;
    this.port = port;
  }
  
  public String doGet(String uri) {
    StringBuilder sb = new StringBuilder();
    HttpClient httpclient = HttpClientBuilder.create().build();
    try {
      // specify the host, protocol, and port
      HttpHost target = new HttpHost(host, port, "http");
       
      // specify the get request
      HttpGet getRequest = new HttpGet(uri);
      LOG.info("executing request to " + target);
      
      HttpResponse httpResponse = httpclient.execute(target, getRequest);
      HttpEntity entity = httpResponse.getEntity();
      LOG.info("doGet HttpEntity:"+entity);
      
      LOG.info("----------------------------------------");
      LOG.info("getStatusLine " + httpResponse.getStatusLine());
      
      Header[] headers = httpResponse.getAllHeaders();
      for (int i = 0; i < headers.length; i++) {
        LOG.debug(""+headers[i]);
      }
      LOG.info("----------------------------------------");
 
      if (entity != null) {
        sb.append(EntityUtils.toString(entity));
      }
 
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      
    }
    return sb.toString();
  }
  

  public String doPost(String url, String data) {
    String result = "";
    HttpClient client = HttpClientBuilder.create().build();
    try {
      HttpHost target = new HttpHost(host, port, "http");
      HttpPost post = new HttpPost(url);
      post.setHeader("Content-type", "application/json;charset=utf-8");
//      post.setHeader("Content-type", "application/x-www-form-urlencoded");
      StringEntity entity = new StringEntity(data,"utf-8");
      entity.setContentType("application/json;charset=utf-8");
//      entity.setContentType("application/x-www-form-urlencoded");
      post.setEntity(entity);
      HttpResponse response = client.execute(target, post);
      StatusLine status = response.getStatusLine();
      result = EntityUtils.toString(response.getEntity()); 
      LOG.info("doPost StringEntity:"+result);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      return result;
    }
    
  }
  
  private void testPost() {
//    .param("customerId","DS-AEB137A7-E0063C13-74FC06E7-1060DEE8")
//    .param("terminalId", "test")
//    .param("name", "test")
//    .param("createUserId", "test")
//    .param("createTime", "0")
//    .param("description", "1")
//    .param("dsType", "1")
//    .param("isOpenLocalBackup", "1")
//    .param("lmUserId", "1")
//    .param("lmTime", "1")
//    .param("spaceUsage", "1")
//    .param("nextRun", "1")
//    .param("count", "1")
//    .param("currentVersionMajor", "1")
//    .param("currentVersionMinor", "1")
//    .param("scanType", "1")
//    .param("root", "1")
//    .param("scanHideFile", "1")
//    .param("verifyCompleteName", "1")
//    .param("verifyCompleteMaxCount", "1")
//    .param("verifyCompleteTimer", "1")
//    .param("fileAttrGainer", "1")
//    .param("recordCanNotReadFileInfo", "1")
//    .param("recordEmptyDirectory", "1")
//    .param("recordEmptyFile", "1")
//    .param("filterFileSuffix", "1")
//    .param("dbUsername", "1")
//    .param("dbPassword", "1")
//    .param("dbType", "1")
//    .param("dbHost", "1")
//    .param("dbPort", "1")
//    .param("dbName", "1")
    
    Datasource ds = new Datasource();
    ds.setTerminalId("test");
    ds.setCustomerId("DS-AEB137A7-E0063C13-74FC06E7-1060DEE8");
    ds.setName("test_rest");
    ds.setCreateUserId("test");
    DatasourceConfig dsc = new DatasourceConfig();
    Gson gson = new Gson();
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("datasource", ds);
    map.put("datasourceConfig", dsc);
    String data = gson.toJson(map);
    String rs = doPost(ApiConstants.URI_ADD_DATASOURCE, data);
    System.out.println(rs);
  }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    RestUtil util = new RestUtil("192.168.0.216", 8080);
    //String rs = util.doGet("/ebeim-api/datasource/find/terminalId?terminalId=TM-430055B5-DA6F5DF68");
    //System.out.println(rs);
    util.testPost();
  }

}
